﻿/**********************************************************************
*创建人：蔡水明
*创建时间：2019/10/17 15:25:38
*说明：<Function>
/**********************************************************************/
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Utilities;

namespace WebApi.Helper
{
    public class HtmlHelper
    {
        /// <summary>
        /// 把html里面的base64替换成实体图片文件并保存对应图片
        /// </summary>
        /// <param name="htmlStr"></param>
        /// <returns></returns>
        public static string ReplaceImgs(string htmlStr)
        {
            if (string.IsNullOrEmpty(htmlStr)) return string.Empty;
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(htmlStr);
            if (htmlDoc.DocumentNode.SelectNodes("//img") != null)
            {
                List<HtmlNode> imgLst = htmlDoc.DocumentNode.SelectNodes("//img").ToList();

                foreach (var item in imgLst)
                {
                    item.SetAttributeValue("preview", "100");
                    string newSrc = item.Attributes["src"].Value;                    
                    
                    newSrc = SaveBase64(newSrc);
                    if (string.IsNullOrEmpty(newSrc) == false)
                        item.Attributes["src"].Value = newSrc;
                }
            }
            return htmlDoc.DocumentNode.OuterHtml;
        }
        private static string SaveBase64(string base64Str)
        {
            string resp = "";
            try
            {
                int firstcomma = base64Str.IndexOf(',');//获取第一个逗号的位置 
                string fileType = ".png";
                if (firstcomma != -1)
                {
                    fileType = base64Str.Substring(0, firstcomma);
                    fileType = fileType.TrimStart("data:image/".ToCharArray());
                    fileType = "." + fileType.TrimEnd(";base64".ToCharArray());
                    base64Str = base64Str.Substring(firstcomma + 1);

                }
                else return resp;
                byte[] bt = Convert.FromBase64String(base64Str);//获取图片base64
                string fileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();//年月
                string ImageFilePath = "/res/static/img/comm/" + fileName;
                resp = ImageFilePath;
                if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(ImageFilePath)) == false)//如果不存在就创建文件夹
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(ImageFilePath));
                }
                fileName = Guid.NewGuid().ToString("N");
                resp += "/" + fileName + fileType;
                string ImagePath = HttpContext.Current.Server.MapPath(ImageFilePath) + "/" + fileName; //定义图片名称
                File.WriteAllBytes(ImagePath + fileType, bt); //保存图片到服务器，然后获取路径 

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            return resp;
        }

        /// <summary>
        /// 清除Html代码里面包含的图片文件
        /// </summary>
        /// <param name="htmlStr"></param>
        public static void ClearImgFiles(string htmlStr)
        {
            if (string.IsNullOrEmpty(htmlStr)) return;
            HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(htmlStr);
            HtmlNodeCollection ns = htmlDoc.DocumentNode.SelectNodes("//img");
            List<HtmlNode> imgLst = new List<HtmlNode>();
            if (ns == null) return;
            imgLst = ns.ToList();
            foreach (var item in imgLst)
            {
                string imgFile = item.Attributes["src"].Value;
                string saveTempPath = "~/" + imgFile;
                string dirTempPath = HttpContext.Current.Server.MapPath(saveTempPath);
                if (File.Exists(dirTempPath))
                    File.Delete(dirTempPath);
            }

        }

        private const string EwmPath = "/res/static/img/comm/Ewm/";//文件保存基本路径
        private const string LogoFileUrl = "/res/static/img/comm/logo.png";//logo文件位置
        private const string Domain = "http://mitaoonline.com";
        private static string storeUrl = $"{Domain}/StoreDetails/";//商家Url
        private static string girlUrl = $"{Domain}/ProductDetails/";//技师Url
        private static string userUrl = $"{Domain}/register/";//用户Url

        private static EwmFile iniFilePath(string dirname, int id)
        {

            if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(EwmPath + dirname + "/")) == false)//如果不存在就创建文件夹
            {
                System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(EwmPath + dirname + "/"));
            }
            EwmFile resp = new EwmFile();
            resp.logoFile = HttpContext.Current.Server.MapPath(LogoFileUrl);
            resp.outFile = HttpContext.Current.Server.MapPath(EwmPath + dirname + "/" + id.ToString() + ".png");
            return resp;
        }
        private static EwmFile iniFilePathByUserID(string dirname, string id)
        {

            if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(EwmPath + dirname + "/")) == false)//如果不存在就创建文件夹
            {
                System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(EwmPath + dirname + "/"));
            }
            EwmFile resp = new EwmFile();
            resp.logoFile = HttpContext.Current.Server.MapPath(LogoFileUrl);
            resp.outFile = HttpContext.Current.Server.MapPath(EwmPath + dirname + "/" + id.ToString() + ".png");
            return resp;
        }
        /// <summary>
        /// 产生商家二维码
        /// </summary>
        /// <param name="storeID"></param>
        public static void CreateStoreEwm(int storeID)
        {
            EwmFile ef = iniFilePath("store", storeID);
            ef.ewmCode = storeUrl + storeID.ToString();
            EwmHelper.Generate(ef.ewmCode, ef.logoFile, ef.outFile);
        }
        /// <summary>
        /// 产生技师二维码
        /// </summary>
        /// <param name="storeID"></param>
        public static void CreateGirlEwm(int girlID)
        {
            EwmFile ef = iniFilePath("girl", girlID);
            ef.ewmCode = girlUrl + girlID.ToString();
            EwmHelper.Generate(ef.ewmCode, ef.logoFile, ef.outFile);
        }
        /// <summary>
        /// 产生用户二维码
        /// </summary>
        /// <param name="storeID"></param>
        public static void CreateUserEwm(string userID)
        {
            EwmFile ef = iniFilePathByUserID("user", userID);
            ef.ewmCode = userUrl + userID;
            EwmHelper.Generate(ef.ewmCode, ef.logoFile, ef.outFile);
        }
    }
    public struct EwmFile
    {
        public string ewmCode;
        public string outFile;
        public string logoFile;
    }
}